import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import { message } from 'antd'
import userService from '@/services/user'
import { User, UserQuery, CreateUserRequest } from '@/types/user'

/**
 * 用户状态接口定义
 */
interface UserState {
  users: User[]
  total: number
  loading: boolean
  error: string | null
}

/**
 * 初始状态定义
 */
const initialState: UserState = {
  users: [],
  total: 0,
  loading: false,
  error: null,
}

// ==================== 异步 Actions ====================

/**
 * 异步action：获取用户列表
 * @param params 查询参数
 */
export const getUserList = createAsyncThunk(
  'user/getUserList',
  async (params: UserQuery, { rejectWithValue }) => {
    try {
      const response = await userService.getUserList(params)
      if (response.code === 200) {
        return response.data
      } else {
        return rejectWithValue(response.message)
      }
    } catch (error: any) {
      return rejectWithValue(error.message || '获取用户列表失败')
    }
  }
)

/**
 * 异步action：根据ID获取用户
 * @param id 用户ID
 */
export const getUserById = createAsyncThunk(
  'user/getUserById',
  async (id: number, { rejectWithValue }) => {
    try {
      const response = await userService.getUserById(id)
      if (response.code === 200) {
        return response.data
      } else {
        return rejectWithValue(response.message)
      }
    } catch (error: any) {
      return rejectWithValue(error.message || '获取用户信息失败')
    }
  }
)

/**
 * 异步action：创建用户
 * @param userData 用户数据
 */
export const createUser = createAsyncThunk(
  'user/createUser',
  async (userData: CreateUserRequest, { rejectWithValue }) => {
    try {
      const response = await userService.createUser(userData)
      if (response.code === 200) {
        message.success('用户创建成功')
        return response.data
      } else {
        return rejectWithValue(response.message)
      }
    } catch (error: any) {
      return rejectWithValue(error.message || '创建用户失败')
    }
  }
)

/**
 * 异步action：更新用户
 * @param param0 包含用户ID和更新数据的对象
 */
export const updateUser = createAsyncThunk(
  'user/updateUser',
  async ({ id, userData }: { id: number; userData: Partial<User> }, { rejectWithValue }) => {
    try {
      const response = await userService.updateUser(id, userData)
      if (response.code === 200) {
        message.success('用户更新成功')
        return response.data
      } else {
        return rejectWithValue(response.message)
      }
    } catch (error: any) {
      return rejectWithValue(error.message || '更新用户失败')
    }
  }
)

/**
 * 异步action：删除用户
 * @param id 用户ID
 */
export const deleteUser = createAsyncThunk(
  'user/deleteUser',
  async (id: number, { rejectWithValue }) => {
    try {
      const response = await userService.deleteUser(id)
      if (response.code === 200) {
        message.success('用户删除成功')
        return id
      } else {
        return rejectWithValue(response.message)
      }
    } catch (error: any) {
      return rejectWithValue(error.message || '删除用户失败')
    }
  }
)

/**
 * 异步action：批量删除用户
 * @param ids 用户ID数组
 */
export const batchDeleteUsers = createAsyncThunk(
  'user/batchDeleteUsers',
  async (ids: number[], { rejectWithValue }) => {
    try {
      const response = await userService.batchDeleteUsers(ids)
      if (response.code === 200) {
        message.success(`成功删除 ${ids.length} 个用户`)
        return ids
      } else {
        return rejectWithValue(response.message)
      }
    } catch (error: any) {
      return rejectWithValue(error.message || '批量删除用户失败')
    }
  }
)

/**
 * 异步action：重置用户密码
 * @param param0 包含用户ID和新密码的对象
 */
export const resetPassword = createAsyncThunk(
  'user/resetPassword',
  async ({ id, newPassword }: { id: number; newPassword: string }, { rejectWithValue }) => {
    try {
      const response = await userService.resetPassword(id, newPassword)
      if (response.code === 200) {
        message.success('密码重置成功')
        return response.data
      } else {
        return rejectWithValue(response.message)
      }
    } catch (error: any) {
      return rejectWithValue(error.message || '重置密码失败')
    }
  }
)

/**
 * 异步action：切换用户状态
 * @param param0 包含用户ID和状态的对象
 */
export const toggleUserStatus = createAsyncThunk(
  'user/toggleUserStatus',
  async ({ id, status }: { id: number; status: number }, { rejectWithValue }) => {
    try {
      const response = await userService.toggleUserStatus(id, status)
      if (response.code === 200) {
        message.success(status === 1 ? '用户已启用' : '用户已禁用')
        return { id, status }
      } else {
        return rejectWithValue(response.message)
      }
    } catch (error: any) {
      return rejectWithValue(error.message || '切换用户状态失败')
    }
  }
)

const userSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {
    /**
     * 清除错误信息
     */
    clearError: (state) => {
      state.error = null
    },
    /**
     * 重置用户状态
     */
    resetUserState: (state) => {
      state.users = []
      state.total = 0
      state.loading = false
      state.error = null
    },
  },
  extraReducers: (builder) => {
    builder
      // ==================== 获取用户列表 ====================
      .addCase(getUserList.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(getUserList.fulfilled, (state, action) => {
        state.loading = false
        state.users = action.payload.items
        state.total = action.payload.total
      })
      .addCase(getUserList.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload as string
        message.error(action.payload as string)
      })
      
      // ==================== 根据ID获取用户 ====================
      .addCase(getUserById.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(getUserById.fulfilled, (state, action) => {
        state.loading = false
        // 如果用户已存在，更新；否则添加
        const index = state.users.findIndex(user => user.id === action.payload.id)
        if (index !== -1) {
          state.users[index] = action.payload
        } else {
          state.users.push(action.payload)
        }
      })
      .addCase(getUserById.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload as string
        message.error(action.payload as string)
      })
      
      // ==================== 创建用户 ====================
      .addCase(createUser.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(createUser.fulfilled, (state, action) => {
        state.loading = false
        state.users.push(action.payload)
        state.total += 1
      })
      .addCase(createUser.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload as string
        message.error(action.payload as string)
      })
      
      // ==================== 更新用户 ====================
      .addCase(updateUser.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(updateUser.fulfilled, (state, action) => {
        state.loading = false
        const index = state.users.findIndex(user => user.id === action.payload.id)
        if (index !== -1) {
          state.users[index] = action.payload
        }
      })
      .addCase(updateUser.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload as string
        message.error(action.payload as string)
      })
      
      // ==================== 删除用户 ====================
      .addCase(deleteUser.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(deleteUser.fulfilled, (state, action) => {
        state.loading = false
        state.users = state.users.filter(user => user.id !== action.payload)
        state.total -= 1
      })
      .addCase(deleteUser.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload as string
        message.error(action.payload as string)
      })
      
      // ==================== 批量删除用户 ====================
      .addCase(batchDeleteUsers.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(batchDeleteUsers.fulfilled, (state, action) => {
        state.loading = false
        state.users = state.users.filter(user => !action.payload.includes(user.id))
        state.total -= action.payload.length
      })
      .addCase(batchDeleteUsers.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload as string
        message.error(action.payload as string)
      })
      
      // ==================== 重置用户密码 ====================
      .addCase(resetPassword.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(resetPassword.fulfilled, (state) => {
        state.loading = false
      })
      .addCase(resetPassword.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload as string
        message.error(action.payload as string)
      })
      
      // ==================== 切换用户状态 ====================
      .addCase(toggleUserStatus.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(toggleUserStatus.fulfilled, (state, action) => {
        state.loading = false
        const index = state.users.findIndex(user => user.id === action.payload.id)
        if (index !== -1) {
          state.users[index].status = action.payload.status
        }
      })
      .addCase(toggleUserStatus.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload as string
        message.error(action.payload as string)
      })
  },
})

// ==================== 导出 Actions ====================
export const { clearError, resetUserState } = userSlice.actions

// ==================== 选择器 ====================
export const selectUsers = (state: { user: UserState }) => state.user.users
export const selectUserTotal = (state: { user: UserState }) => state.user.total
export const selectUserLoading = (state: { user: UserState }) => state.user.loading
export const selectUserError = (state: { user: UserState }) => state.user.error

export default userSlice.reducer